package com.inspur.edp.common.expr.visitor.field;

import com.inspur.edp.common.expr.ast.CompileUnitParser;
import com.inspur.edp.common.expr.parser.ExpressAstParser;
import com.inspur.edp.common.expr.visitor.JavaVisitor;
import com.inspur.edp.common.expr.visitor.VisitResult;
import com.inspur.edp.common.type.Field;
import com.inspur.edp.common.type.Type;
import com.inspur.edp.common.type.TypeRefer;

/**
 * @author lizhaorui
 * @description TODO
 * @date 2024/6/4 15:48
 */
public class FieldAccessManager {

    public static VisitResult visitGetter(JavaVisitor visitor,
                                          CompileUnitParser.FieldAccessExprContext fieldAccessExprContext,
                                          CompileUnitParser.ExpressContext objectExpr,
                                          String fieldName) {
        Field field = getField(visitor, objectExpr, fieldName);
        String accessKind = field.getAccessKind();
        return FieldAccessFactory.getSpi(accessKind).visitGetter(
                visitor,
                visitor,
                fieldAccessExprContext,
                objectExpr,
                field
        );
    }

    public static VisitResult visitSetter(JavaVisitor visitor, CompileUnitParser.ExpressContext objectExpr, String fieldName, CompileUnitParser.ExpressContext valueExpr) {
        Field field = getField(visitor, objectExpr, fieldName);
        String accessKind = field.getAccessKind();
        return FieldAccessFactory.getSpi(accessKind).visitSetter(
                visitor,
                visitor,
                objectExpr,
                field,
                valueExpr
        );
    }

    private static Field getField(JavaVisitor visitor, CompileUnitParser.ExpressContext objectExpr, String fieldName) {
        TypeRefer objectType = ExpressAstParser.getOriginalType(objectExpr, visitor);
        Type dslType = visitor.getType(objectType);
        return dslType.getField(fieldName);
    }

}
